package com.eamois.dao.manual.impl;

import java.sql.SQLException;
import java.util.Collection;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;

import com.eamois.dao.impl.BaseDaoImpl;
import com.eamois.dao.manual.StoppageTypeDao;
import com.eamois.domain.manual.StoppageType;

public class StoppageTypeDaoImpl extends BaseDaoImpl<StoppageType> implements StoppageTypeDao{

	@SuppressWarnings("unchecked")
	public Collection<StoppageType> findRootStoppageType() {
		// TODO Auto-generated method stub
		return (Collection<StoppageType>) this.getHibernateTemplate().execute(new HibernateCallback() {

			@Override
			public Object doInHibernate(Session arg0)
					throws HibernateException, SQLException {
				// TODO Auto-generated method stub
				Criteria criteria = arg0.createCriteria(StoppageType.class);
				criteria.add(Restrictions.isNull("parentType"));
				return criteria.list();
			}
			
		});
	}

	@SuppressWarnings("unchecked")
	public Collection<StoppageType> findChildStoppageType(
			final StoppageType stoppageType) {
		// TODO Auto-generated method stub
		return (Collection<StoppageType>) this.getHibernateTemplate().execute(new HibernateCallback() {

			@Override
			public Object doInHibernate(Session arg0)
					throws HibernateException, SQLException {
				// TODO Auto-generated method stub
				Criteria criteria = arg0.createCriteria(StoppageType.class);
				criteria.add(Restrictions.eq("parentType", stoppageType));
				return criteria.list();
			}
			
		});
	}

	@SuppressWarnings("unchecked")
	public Collection<StoppageType> findAllStoppageType() {
		// TODO Auto-generated method stub
		return (Collection<StoppageType>)this.getHibernateTemplate().execute(new HibernateCallback() {
			
			@Override
			public Object doInHibernate(Session session) throws HibernateException,
					SQLException {
				// TODO Auto-generated method stub
				Criteria criteria = session.createCriteria(StoppageType.class);
				return criteria.list();
			}
		});
	}

	@SuppressWarnings("unchecked")
	@Override
	public StoppageType findTypeByName(final String name) {
		// TODO Auto-generated method stub
		return (StoppageType)this.getHibernateTemplate().execute(new HibernateCallback() {
			
			@Override
			public Object doInHibernate(Session session) throws HibernateException,
					SQLException {
				// TODO Auto-generated method stub
				Criteria criteria = session.createCriteria(StoppageType.class);
				criteria.add(Restrictions.eq("name", name));
				if(criteria.list()!=null&&criteria.list().size()!=0){
					return criteria.list().get(0);
				}else{
					return null;
				}
			}
		});
	}

}
